package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.Config;
import com.gaogzhen.mapper.ConfigMapper;
import com.gaogzhen.service.ConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService{

    @Override
    public Page<Config> findByPage(Page<Config> page, String type, String code, String name) {
        return page(page, Wrappers.lambdaQuery(Config.class)
                            .like(StringUtils.isNotBlank(type), Config::getType, type)
                            .like(StringUtils.isNotBlank(code), Config::getCode, code)
                            .like(StringUtils.isNotBlank(name), Config::getName, name)
        );
    }

    @Override
    public void add(Config config) {
        boolean save = save(config);
        if (!save) {
            throw new RuntimeException("新增配置参数失败！");
        }
    }

    @Override
    public void updateConfig(Config config) {
        boolean update = updateById(config);
        if (!update) {
            throw new RuntimeException("修改配置参数失败！");
        }
    }

    @Override
    public Config getByCode(String code) {
        return getOne(new LambdaQueryWrapper<Config>().eq(Config::getCode, code));
    }

    @Override
    public Map<String, Config> getByCodes(String... code) {
        List<Config> configs = list(new LambdaQueryWrapper<Config>()
                .in(code.length > 0, Config::getCode, Arrays.asList(code))
        );
        if (CollectionUtils.isEmpty(configs)) {
            return null;
        }
        return configs.stream().collect(Collectors.toMap(Config::getCode, Function.identity()));
    }
}
